import 'package:flutter/material.dart';

class HorizontalProgressBar extends StatefulWidget {
  final double progress; // 进度值 0.0 - 1.0
  final double width; // 进度条宽度
  final double height; // 进度条高度
  final Duration animationDuration; // 动画持续时间
  final List<Color> gradientColors; // 渐变色彩
  final Color backgroundColor; // 背景色
  final TextStyle? textStyle; // 文字样式
  final bool showPercentage; // 是否显示百分比
  final bool showShadow; // 是否显示阴影
  final double borderRadius; // 圆角半径
  final TextPosition textPosition; // 文字位置
  final bool animateGradient; // 是否启用渐变动画
  final Color? borderColor; // 边框颜色
  final double borderWidth; // 边框宽度

  const HorizontalProgressBar({
    super.key,
    required this.progress,
    this.width = 300.0,
    this.height = 20.0,
    this.animationDuration = const Duration(milliseconds: 1000),
    this.showShadow = true,
    this.gradientColors = const [
      Color(0xFF6B73FF),
      Color(0xFF9B59B6),
      Color(0xFFE91E63),
    ],
    this.backgroundColor = const Color(0xFFE8E8E8),
    this.textStyle,
    this.showPercentage = true,
    this.borderRadius = 10.0,
    this.textPosition = TextPosition.center,
    this.animateGradient = false,
    this.borderColor,
    this.borderWidth = 1.0,
  });

  @override
  State<HorizontalProgressBar> createState() => _HorizontalProgressBarState();
}

// 文字位置枚举
enum TextPosition {
  center,    // 中心
  right,     // 右侧
  left,      // 左侧
  inside,    // 进度条内部
  outside,   // 进度条外部
}

class _HorizontalProgressBarState extends State<HorizontalProgressBar>
    with TickerProviderStateMixin {
  late AnimationController _progressController;
  late AnimationController _gradientController;
  late Animation<double> _progressAnimation;
  late Animation<double> _gradientAnimation;
  double _currentProgress = 0.0;

  @override
  void initState() {
    super.initState();

    // 进度动画控制器
    _progressController = AnimationController(
      duration: widget.animationDuration,
      vsync: this,
    );

    // 渐变动画控制器（可选）
    _gradientController = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    );

    _progressAnimation = Tween<double>(
      begin: 0.0,
      end: widget.progress,
    ).animate(CurvedAnimation(
      parent: _progressController,
      curve: Curves.easeInOut,
    ));

    _gradientAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _gradientController,
      curve: Curves.linear,
    ));

    _progressAnimation.addListener(() {
      setState(() {
        _currentProgress = _progressAnimation.value;
      });
    });

    // 启动动画
    _progressController.forward();

    if (widget.animateGradient) {
      _gradientController.repeat();
    }
  }

  @override
  void didUpdateWidget(HorizontalProgressBar oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.progress != widget.progress) {
      _updateProgress();
    }

    if (oldWidget.animateGradient != widget.animateGradient) {
      if (widget.animateGradient) {
        _gradientController.repeat();
      } else {
        _gradientController.stop();
      }
    }
  }

  void _updateProgress() {
    _progressAnimation = Tween<double>(
      begin: _currentProgress,
      end: widget.progress,
    ).animate(CurvedAnimation(
      parent: _progressController,
      curve: Curves.easeInOut,
    ));

    _progressController.reset();
    _progressController.forward();
  }

  @override
  void dispose() {
    _progressController.dispose();
    _gradientController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 进度条外部文字（上方）
          if (widget.textPosition == TextPosition.outside && widget.showPercentage) ...[
            _buildPercentageText(),
            const SizedBox(height: 4),
          ],

          // 进度条主体
          Container(
            width: widget.width,
            height: widget.height,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(widget.borderRadius),
              border: widget.borderColor != null
                  ? Border.all(color: widget.borderColor!, width: widget.borderWidth)
                  : null,
              boxShadow: widget.showShadow
                  ? [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ]
                  : null,
            ),
            child: Stack(
              children: [
                // 背景
                Container(
                  width: widget.width,
                  height: widget.height,
                  decoration: BoxDecoration(
                    color: widget.backgroundColor,
                    borderRadius: BorderRadius.circular(widget.borderRadius),
                  ),
                ),

                // 进度条
                AnimatedBuilder(
                  animation: widget.animateGradient ? _gradientAnimation : _progressAnimation,
                  builder: (context, child) {
                    return CustomPaint(
                      size: Size(widget.width, widget.height),
                      painter: HorizontalProgressPainter(
                        progress: _currentProgress,
                        gradientColors: widget.gradientColors,
                        borderRadius: widget.borderRadius,
                        animateGradient: widget.animateGradient,
                        gradientOffset: widget.animateGradient ? _gradientAnimation.value : 0.0,
                      ),
                    );
                  },
                ),

                // 进度条内部文字
                if (widget.textPosition == TextPosition.inside && widget.showPercentage)
                  Center(child: _buildPercentageText()),

                // 进度条中心文字
                if (widget.textPosition == TextPosition.center && widget.showPercentage)
                  Center(child: _buildPercentageText()),
              ],
            ),
          ),

          // 进度条左右两侧文字
          if ((widget.textPosition == TextPosition.left || widget.textPosition == TextPosition.right) && widget.showPercentage) ...[
            const SizedBox(height: 4),
            Container(
              width: widget.width,
              child: Row(
                mainAxisAlignment: widget.textPosition == TextPosition.left
                    ? MainAxisAlignment.start
                    : MainAxisAlignment.end,
                children: [
                  _buildPercentageText(),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildPercentageText() {
    return Text(
      '${(_currentProgress * 100).round()}%',
      style: widget.textStyle ??
          TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: widget.textPosition == TextPosition.inside
                ? Colors.white
                : const Color(0xFF2D3748),
          ),
    );
  }
}

class HorizontalProgressPainter extends CustomPainter {
  final double progress;
  final List<Color> gradientColors;
  final double borderRadius;
  final bool animateGradient;
  final double gradientOffset;

  HorizontalProgressPainter({
    required this.progress,
    required this.gradientColors,
    required this.borderRadius,
    required this.animateGradient,
    required this.gradientOffset,
  });

  // 创建平滑的渐变色彩数组
  List<Color> _createSmoothGradient(List<Color> colors, int segments) {
    if (colors.length < 2) return colors;

    List<Color> smoothColors = [];

    for (int i = 0; i < colors.length - 1; i++) {
      Color startColor = colors[i];
      Color endColor = colors[i + 1];

      // 在每两个颜色之间插入过渡色
      for (int j = 0; j < segments; j++) {
        double t = j / segments;
        Color interpolatedColor = Color.lerp(startColor, endColor, t)!;
        smoothColors.add(interpolatedColor);
      }
    }

    // 添加最后一个颜色
    smoothColors.add(colors.last);
    return smoothColors;
  }

  // 创建对应的停靠点
  List<double> _createSmoothStops(List<Color> originalColors, int segments) {
    List<double> stops = [];
    int totalSegments = (originalColors.length - 1) * segments + 1;

    for (int i = 0; i < totalSegments; i++) {
      stops.add(i / (totalSegments - 1));
    }

    return stops;
  }

  @override
  void paint(Canvas canvas, Size size) {
    if (progress == 0) return;

    final progressWidth = size.width * progress;
    final rect = RRect.fromRectAndRadius(
      Rect.fromLTWH(0, 0, progressWidth, size.height),
      Radius.circular(borderRadius),
    );

    // 创建平滑的渐变色彩
    const int segmentsPerColor = 15;
    final smoothColors = _createSmoothGradient(gradientColors, segmentsPerColor);
    final smoothStops = _createSmoothStops(gradientColors, segmentsPerColor);

    // 创建渐变
    Gradient gradient;
    if (animateGradient) {
      // 动画渐变效果
      final animatedColors = <Color>[];
      final animatedStops = <double>[];

      for (int i = 0; i < smoothColors.length; i++) {
        final adjustedStop = (smoothStops[i] + gradientOffset) % 1.0;
        animatedStops.add(adjustedStop);
        animatedColors.add(smoothColors[i]);
      }

      // 排序以确保stops是递增的
      final combined = List.generate(animatedColors.length, (i) => [animatedStops[i], animatedColors[i]]);
      combined.sort((a, b) => (a[0] as double).compareTo(b[0] as double));

      gradient = LinearGradient(
        colors: combined.map((item) => item[1] as Color).toList(),
        stops: combined.map((item) => item[0] as double).toList(),
        begin: Alignment.centerLeft,
        end: Alignment.centerRight,
      );
    } else {
      gradient = LinearGradient(
        colors: smoothColors,
        stops: smoothStops,
        begin: Alignment.centerLeft,
        end: Alignment.centerRight,
      );
    }

    final paint = Paint()
      ..shader = gradient.createShader(Rect.fromLTWH(0, 0, size.width, size.height))
      ..style = PaintingStyle.fill;

    canvas.drawRRect(rect, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

// 使用示例
class ProgressBarExample extends StatefulWidget {
  @override
  _ProgressBarExampleState createState() => _ProgressBarExampleState();
}

class _ProgressBarExampleState extends State<ProgressBarExample> {
  double _progress = 0.7;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('水平进度条示例')),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 基础进度条
            HorizontalProgressBar(
              progress: _progress,
              width: 300,
              height: 20,
            ),

            // 无文字进度条示例
            const Text('无文字进度条', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            const SizedBox(height: 10),
            HorizontalProgressBar(
              progress: _progress,
              width: 300,
              height: 15,
              showPercentage: false, // 不显示百分比文字
              gradientColors: [
                Colors.green.shade300,
                Colors.green.shade600,
                Colors.green.shade800,
              ],
            ),

            const SizedBox(height: 30),

            // 自定义样式进度条
            HorizontalProgressBar(
              progress: _progress,
              width: 300,
              height: 25,
              textPosition: TextPosition.right,
              borderRadius: 15,
              gradientColors: [
                Colors.orange,
                Colors.red,
                Colors.purple,
              ],
            ),

            const SizedBox(height: 30),

            // 动画渐变进度条
            HorizontalProgressBar(
              progress: _progress,
              width: 300,
              height: 30,
              textPosition: TextPosition.inside,
              animateGradient: false,
              borderColor: Colors.grey.shade300,
              gradientColors: [
                Colors.cyan,
                Colors.blue,
                Colors.indigo,
              ],
            ),

            const SizedBox(height: 50),

            // 控制按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      _progress = (_progress - 0.1).clamp(0.0, 1.0);
                    });
                  },
                  child: const Text('-10%'),
                ),
                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      _progress = (_progress + 0.1).clamp(0.0, 1.0);
                    });
                  },
                  child: const Text('+10%'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}